<?php
/**
* 解析xml 格式
*/
class CcbXml
{
    /**
     * XMLParser 操作句柄
     */
    private $_xml;

    private $_encoding = 'GB2312';

    private $_version = '1.0';

    private $_standalone = TRUE;

    function __construct($version = '1.0', $encoding = 'GB2312', $standalone = TRUE)
    {
        $this->_version = $version;
        $this->_encoding = $encoding;
        $this->_standalone = $standalone;
    }

    public function buildXml($xmlData, $parentTag = 'TX')
    {
        $this->setXmlHeader();
        $body = $this->xml->appendChild($this->xml->createElement($parentTag));
        $this->setXmlAttributes($xmlData, $body);
        $this->xml->formatOutput = true;
        return $this->xml->saveXml();
    }

    private function setXmlHeader()
    {
        $this->xml = new DOMDocument($this->_version, $this->_encoding);
        $this->xml->standalone = TRUE;
    }

    /**
     * 设置xml 属性
     */
    private function setXmlAttributes($xmlData, $body)
    {
        foreach ($xmlData as $key => $value) {
            if ( is_array($value) ) {
                $parentTag = $body->appendChild($this->xml->createElement($key));
                $this->setXmlAttributes($value, $parentTag);
            } else {
                $as = $body->appendChild($this->xml->createElement($key));
                $as->appendChild($this->xml->createTextNode($value));
            }
        }
    }

    /**
     * 解析 字符xml
     */
    public function simplexmlLoadString($strXml)
    {
        $strXml = simplexml_load_string($strXml, null, LIBXML_NOERROR);
        if ( ! is_object($strXml) ) {
            throw new Exception("外联平台返回格式解析错误.点击交易查询,确认交易是否成功", 100); //xml解析错误
        }
        return $strXml;
    }

    /**
     * 将反馈回来的字符格式 改变成utf8
     */
    public function setXmlEncoding($xml, $inCharset = 'GB2312', $outCharset = 'UTF8')
    {
        foreach ($xml as $key => $value) {
            if ( $value->count() > 0 ) {
                $this->setXmlEncoding($value);
            } else {
                $xml->$key = iconv($inCharset, $outCharset, $value);
            }
        }
        return $xml;
    }
}